<template>
  <div class="file-selector">
    <el-input
      :model-value="modelValue"
      @update:model-value="$emit('update:modelValue', $event)"
      :placeholder="placeholder"
      clearable
      class="file-input"
    >
      <template #append>
        <el-popover
          placement="bottom"
          :width="300"
          trigger="click"
        >
          <template #reference>
            <el-button>
              历史路径
            </el-button>
          </template>
          <div class="history-paths">
            <p v-if="recentPaths.length === 0">暂无历史记录</p>
            <el-scrollbar height="200px">
              <div
                v-for="(path, index) in recentPaths"
                :key="index"
                class="history-path-item"
                @click="selectPath(path)"
              >
                <el-tooltip :content="path" placement="left">
                  <span>{{ path }}</span>
                </el-tooltip>
              </div>
            </el-scrollbar>
          </div>
        </el-popover>
      </template>
    </el-input>
  </div>
</template>
  
  <script>
  export default {
    name: 'FileSelector',
    props: {
      modelValue: {
        type: String,
        default: ''
      },
      placeholder: {
        type: String,
        default: '请输入路径'
      },
      storageKey: {
        type: String,
        default: 'recentPaths'
      },
      maxHistory: {
        type: Number,
        default: 10
      }
    },
    emits: ['update:modelValue'],
    data() {
      return {
        recentPaths: []
      };
    },
    mounted() {
      this.loadRecentPaths();
    },
    methods: {
      selectPath(path) {
        this.$emit('update:modelValue', path);
        this.savePathToHistory(path);
      },
      loadRecentPaths() {
        try {
          const storedPaths = localStorage.getItem(this.storageKey);
          if (storedPaths) {
            this.recentPaths = JSON.parse(storedPaths);
          }
        } catch (e) {
          console.error('Failed to load recent paths', e);
        }
      },
      savePathToHistory(path) {
        if (!path || this.recentPaths.includes(path)) return;
        
        this.recentPaths.unshift(path);
        if (this.recentPaths.length > this.maxHistory) {
          this.recentPaths = this.recentPaths.slice(0, this.maxHistory);
        }
        
        try {
          localStorage.setItem(this.storageKey, JSON.stringify(this.recentPaths));
        } catch (e) {
          console.error('Failed to save path to history', e);
        }
      }
    }
  };
  </script>
  
  <style scoped>
  .file-selector {
    display: flex;
    width: 100%;
  }
  
  .file-input {
    flex: 1;
  }
  
  .history-paths {
    max-height: 200px;
  }
  
  .history-path-item {
    padding: 8px 12px;
    cursor: pointer;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
  }
  
  .history-path-item:hover {
    background-color: #f5f7fa;
  }
  </style>